package com.xsp.controller;

import com.xsp.entity.CommonResult;
import com.xsp.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author xsp
 * @date 2024/2/25
 * @desc 处理文件上传的控制器
 */

// 等于@Controller和@ResponseBody的合体
@RestController
@RequestMapping("upload")
public class UploadController {

    @PostMapping("image")
    public CommonResult uploadImg(HttpServletRequest request,
                                  @RequestParam(value = "photo", required = false) MultipartFile file){
        if (!file.isEmpty()) {
            // 设置保存路径
            String path = request.getServletContext().getRealPath("/statics/images");
            String newFileName = UUID.randomUUID().toString() + file.getOriginalFilename();
            File saveFile = new File(path, newFileName);
            try {
                file.transferTo(saveFile);
                return CommonResult.success(saveFile.getName(), "保存成功");
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
        return CommonResult.error("请上传图片！");

    }
}
